<script setup>
import {getCurrentInstance, ref} from "vue";
import {cloneDeep} from "lodash";
import {getSysFile, moveFile, renameFile} from "@/api/system/file_list";
import {listFileCate} from "@/api/system/file_cate";

const {proxy} = getCurrentInstance();
const emit = defineEmits(['success']);
const modalRef = ref();
const formRef = ref();
const formData = ref({
  id: undefined,
  type: '',
  name: '',
})
const formType = ref('rename')
const fileCateOptions = ref([]);
const moveFileIds = ref([]);

const open = async (fileId, type = 'rename', sourceType) => {
  formType.value = type;
  resetForm();
  if (type === 'move') {
    formData.value.type = sourceType;
    moveFileIds.value = fileId;
    fileCateOptions.value.length = 0;
    const {data} = await listFileCate({pageSize: -1, type: sourceType})
    fileCateOptions.value = data.list;
  } else {
    const {data} = await getSysFile(fileId);
    formData.value = {
      ...data
    }
  }
  modalRef.value.handleOpen()
}

const handleSubmit = async () => {
  // 根据formType类型校验
  await formRef.value.validate();
  let data = cloneDeep(formData.value);
  if (formType.value === 'rename') {
    await renameFile(data);
    proxy.$modal.okNotify('修改成功');
  } else {
    await moveFile(moveFileIds.value, data);
    proxy.$modal.okNotify('修改成功');
  }
  resetForm();
  modalRef.value.handleClose();
  emit('success')
}

const resetForm = () => {
  formRef.value?.resetFields();
  formData.value = {
    id: undefined,
    type: '',
    name: ''
  }
}

defineExpose({open})
</script>

<template>
  <dialog-form ref="modalRef" :modalTitle="`${formType === 'rename' ? '文件重命名' : '移动'}`" modalWidth="500px"
               @submit="handleSubmit">
    <a-form ref="formRef" :model="formData" label-width="80px">
      <template v-if="formType === 'rename'">
        <a-form-item label="文件名称" field="name"
                      :rules="{required:formType === 'rename',message:'请输入文件名称',trigger:'blur'}">
          <a-input v-model="formData.name" placeholder="请输入文件名称"/>
        </a-form-item>
      </template>
      <template v-if="formType === 'move'">
        <a-form-item label="文件分类" field="cid"
                      :rules="{required:formType === 'move',message:'请选择文件分类',trigger:'blur'}">
          <a-select v-model="formData.cid" placeholder="请选择文件分类">
            <a-option v-for="(item,index) in fileCateOptions" :key="index" :label="item.name" :value="item.id"/>
          </a-select>
        </a-form-item>
      </template>
    </a-form>
  </dialog-form>
</template>

<style scoped lang="scss">

</style>
